﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace RemoteCode
{
    //Thanks to DragonHunter!

    internal class SyncObject
    {
        public SyncObject(int id)
        {
            this.Id = id;
            this.ReturnObject = null;
            this.Pulsed = false;
        }

        public int Id { get; protected set; }
        public object ReturnObject { get; protected set; }
        public bool Pulsed { get; protected set; }

        private object Sync = new object();
        private bool _abort = false;

        public void Abort()
        {
            _abort = true;
        }
        public void Pulse(object ret)
        {
            lock (Sync)
            {
                ReturnObject = ret;
                Monitor.Pulse(Sync);

                Pulsed = true;
            }
        }
        public bool Wait(int timeOut = 0)
        {
            lock (Sync)
            {
                int time = 0;
                while (true)
                {
                    if (Pulsed)
                        break;
                    if (Monitor.Wait(Sync, 50))
                        break;
                    time += 50;

                    if (timeOut != 0 && time > timeOut)
                        return false;
                    if (_abort)
                        throw new Exception("Aborted");
                }
                return true;
            }
        }
    }
}
